﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.PhsicalGrid;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.PhsicalGrid
{
    /// <summary>
    /// 删除物理网格的处理类
    /// </summary>
    public class DelPhysicalGridHandler : IRequestHandler<DelPhysicalGridCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicallGridModel> physicalGridRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DelPhysicalGridHandler> logger;

        public DelPhysicalGridHandler(IBaseRepository<PhysicallGridModel> physicalGridRepo,IMapper mapper,ILogger<DelPhysicalGridHandler> logger)
        {
            this.physicalGridRepo = physicalGridRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 删除物理网格的处理方法
        /// </summary>
        /// <param name="request">物理网格请求命令表单</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>响应包装类</returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(DelPhysicalGridCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();//实例化响应包装类

            var model = await physicalGridRepo.GetModel(request.Id);//根据主键Id查找要删除的实体数据
            if (model == null)
            {
                res.Msg = "您要删除的网格不存在!";//不存在,不能删除
                res.Code = ApiEnum.Failed;
                return res;
            }

            model.IsDeleted = true;


            int r = await physicalGridRepo.UpdateAsync(model);//使用仓储的删除方法,把物理网格实体删除完保存到数据库中

            if (r > 0)
            {
                res.Msg = "删除物理网格功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "删除物理网格失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;
        }
    }
}
